const Router = require('koa-router');
const login = new Router();
const sqldata = require('./sqldata');

login.get('/', async (ctx)=>{
    let val=ctx.request.body;
    let mydata = await new Promise((resolve, reject)=>{
        let sql = `select * from login`;
        return sqldata(sql, (err, data)=>{
            if(err) reject(err);
            resolve(data);	
        })
    })
    ctx.body = mydata;
})
login.post('/', async (ctx)=>{
    let val=ctx.request.body;
    console.log(val)
    let mydata = await new Promise((resolve, reject)=>{
        let sql = `select * from login where user='${val.username}' and passname='${val.passname}'`;
        return sqldata(sql, (err, data)=>{
            if(err) reject(err);
            resolve(data);	
        })
    })
    console.log(mydata)
    ctx.body = mydata;
})
login.post('/addUser', async (ctx)=>{
    let val=ctx.request.body;
    console.log(val)
    let mydata = await new Promise((resolve, reject)=>{
        let sql = `insert into login values('${val.username}','${val.passname}')`;
        return sqldata(sql, (err, data)=>{
            if(err) reject(err);
            resolve(data);	
        })
    })
    console.log(mydata)
    ctx.body = mydata;
})
login.delete('/delUser', async (ctx)=>{
    let val=JSON.parse(ctx.request.body);
    console.log(val)
    let mydata = await new Promise((resolve, reject)=>{
        let sql = `delete from login where user='${val.username}'`;
        return sqldata(sql, (err, data)=>{
            if(err) reject(err);
            resolve(data);	
        })
    })
    console.log(mydata)
    ctx.body = mydata;
})

module.exports = login;
